jQuery.sap.require("sap.ui.commons.MessageBox");

//------------------- Create and initialize Common Functions ---------------------- //

function initializeCommonFunctions()
{
	function trim() 
	{ 
		var retVal = "";
		
		if(this != null && this.constructor === String)
			retVal = this.replace(/^\s+|\s+$/g,"");
		
		return retVal;
	}
	
	function searchElement(propertyName, propertyValue)
	{
		var retVal = null;
		
		for(var i = 0 ; i < this.length ; i++)
			if(this[i][propertyName] == propertyValue)
			{
				retVal = this[i];
				break;
			}
				
		return retVal;
	}
	
	String.prototype.trim = trim;
	Array.prototype.searchElement = searchElement;
}

initializeCommonFunctions();

//------------------- Common methods used directly ---------------------- //

function onlyNumbers(evt)
{
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function showErrorMessage(message, title)
{
	try{sap.ui.commons.MessageBox.show(message, sap.ui.commons.MessageBox.Icon.ERROR, title);}
	catch(ex){alert(message);}
}

function showSpecifcErrorMessage(response)
{
	var hasError = true;
	
	if(response == "JSON_ERROR")
 		showErrorMessage("There was a problem while trying to read the data from the page and the action cannot be completed. See log for more details.", "Data Retrival Error");
	else if(response == "CALCULATION_ERROR")
 		showErrorMessage("There was a problem while trying to update the result. See log for more details.", "Calculation Error");
 	else if(response == "DATABASE_ERROR")
 		showErrorMessage("There was a problem while fetching the data from the database. See log for more details.", "Database Error");
	else if(response == "ERROR")	
 		showErrorMessage("An unknow error has occurred, please see log for more details.", "Application Error");
	else
		hasError = false;
	
	return hasError;
}

function closeWindow()
{
	window.close();
}

function closeDialog(oControlEvent)
{
	var modalWindow = oControlEvent.getSource().getParent();
	modalWindow.close();
}

function initializePage(elementId, pageName)
{
	function changeCurrentTab(elementId){ document.getElementById(elementId).id = "current"; }
	function setPageName(pageName)
	{ 
		if(pageName.trim() != "")
			window.name = pageName; 
	}
	
	changeCurrentTab(elementId);
	setPageName(pageName);
}

function getXmlHttpRequestObject() 
{  
    if (window.XMLHttpRequest)   
        return new XMLHttpRequest();  
    else if(window.ActiveXObject)   
        return new ActiveXObject("Microsoft.XMLHTTP");  
     else
    	 showErrorMessage("Your Browser not upgraded", "Validation Error");
}

/*
 * This function sends a request to the server and the data is treated according to the caller's reqHandler function. 
 * If no such a function is specified, the request's response is ignored.
 * The parameters must be JSON objects and must follow the pattern: &parameterName=parameterValue
*/
function sendRequest(reqObject, servlet, method, reqHandler, parameters)
{
	if(reqObject == null)
		reqObject = getXmlHttpRequestObject(); 
	
	if (reqObject.readyState == 4 || reqObject.readyState == 0)   
    {  
		var param = "comando=" + method;
		if(parameters != null)  
			param += parameters;
		
		reqObject.open("POST", servlet, false);
		reqObject.onreadystatechange = reqHandler;
		reqObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		reqObject.setRequestHeader("Content-length", param.length);
		reqObject.setRequestHeader("Connection", "close");
		reqObject.send(param);
    }	
}

/*
* Function that simulates the GUID generation for TEMPORARY unique identification in client side
*/
function generateID()
{
	//return new Date().getTime();
    var S4 = function ()
    {
        return Math.floor(Math.random() * 0x10000 /* 65536 */).toString(16);
    };

    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function transformJSON(json)
{
	return encodeURIComponent(JSON.stringify(json));
}

function transformObjectFromString(jsonString)
{
	return JSON.parse(jsonString);
}

function refreshPage()
{
	window.location.href = document.forms[0].action + "?comando=loadData";
}

function requestChangeModule(servletName)
{
	var canChange = false;
	
	function callback(oAction)
	{
		switch(oAction)
		{
			case sap.ui.commons.MessageBox.Action.YES:
				canChange = validateForm();
				break;
			case sap.ui.commons.MessageBox.Action.NO:
				canChange = true;
				break;
		}
		
		if(canChange)
			window.location.href = servletName + "?comando=loadData";
	}
	
	var pendingChanges = verifyPendingChanges();
	
	if(pendingChanges == "ABORT")
		canChange = false;
	else if(pendingChanges)
		sap.ui.commons.MessageBox.show("Do you want to save the changes made to the BC?", sap.ui.commons.MessageBox.Icon.QUESTION, "Pending changes", [sap.ui.commons.MessageBox.Action.YES, sap.ui.commons.MessageBox.Action.NO], callback);
	else
		canChange = true;
				
	return canChange;
}

function newBC()
{
	sendRequest(null, "base", "clearCache");
	refreshPage();
}

function requestOpenBC()
{
	var loadBcReq = getXmlHttpRequestObject();
	
	function handleRequest()  
	{  
		if (loadBcReq.readyState == 4 && loadBcReq.status == 200) 
		{
			eval("var response = (" + loadBcReq.responseText + ")");
		    if(response != "ERROR")
			{
	    		var oDialog1 = null;
	    		var selectedIndex = -1;
	    		
	    		function loadBcData(oControlEvent)
	    		{
	    			if(selectedIndex != -1)
	    			{
	    				sendRequest(null, "base", "loadBcData", null, "&bcID=" + response[selectedIndex].ID);
		    			closeDialog(oControlEvent);
		    			refreshPage();
	    			}
	    			else
	    				showErrorMessage("No Business Case selected. Please select a business case from the list.","Validation Error");
	    		}
	    		
    			oListBox = new sap.ui.commons.ListBox();
    			oListBox.setTooltip("Select a business case to open");
    			oListBox.setWidth("200px");
    			oListBox.setHeight("200px");
    			oListBox.attachSelect(function(oEvent) {selectedIndex = oEvent.getSource().getSelectedIndex();});
    			
    			for (var i = 0; i < response.length; i++) 
    			{
    				oItem = new sap.ui.core.ListItem();
    				oItem.setText(response[i].name);
    				oListBox.addItem(oItem);
    			}
    			
    			var oBtnOpen = new sap.ui.commons.Button({text: "Open", press:loadBcData});
    			var oBtnCancel = new sap.ui.commons.Button({text: "Cancel", press:closeDialog});
    			
    			oDialog1 = new sap.ui.commons.Dialog({modal: true});
    			oDialog1.setTitle("Open Business Case");
    			oDialog1.setWidth("250px");	
    			oDialog1.setHeight("330px");
    			oDialog1.setMinWidth("240px");
    			oDialog1.setMinHeight("300px");
    			oDialog1.setMaxWidth("350px");
    			oDialog1.setMaxHeight("400px");
    			
    			oDialog1.addButton(oBtnOpen);
    			oDialog1.addButton(oBtnCancel);
    			oDialog1.addContent(new sap.ui.commons.Label({text : '   Select a Business Case: '}));
    			oDialog1.addContent(oListBox);
    			oDialog1.setDefaultButton(oBtnOpen);
    			
    		    oDialog1.open();
			}
		    else
		    	showErrorMessage("There was an error while trying to fetch the data from the database and the Business Cases couldn't be loaded. Please see log for more details.", "Database Error");
		}
	}
	
	sendRequest(loadBcReq, "base", "loadBCs", handleRequest);
}

function showValidationError(fields)
{
	if(fields != null && fields != "")
	{
		var errorMessage = "Please fill out the following fields: \n\n";
		var arrFields = fields.split(",");  
		
		for(var i = 0 ; i < arrFields.length ; i++)
			errorMessage += "- " + arrFields[i] + "\n";
		
		showErrorMessage(errorMessage,"Validation Error");
	}
}